package com.zpark.controller;

import com.zpark.bean.Person;
import com.zpark.bean.User;
import com.zpark.service.GroupA;
import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: Abigale
 * @Date: 2022/10/22 10:34
 * @Version: 1.0
 */
@RestController
@Validated
@Slf4j
public class UserCheckController {

    @PostMapping(path = "/check")  // 在@RequestBody 后面加上@Valid注解标识需要进行校验
    public String check(@Validated @RequestBody User user, BindingResult result){

        String name = user.getName();
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                System.out.println(error.getCode() + "_" + error.getDefaultMessage());
            }
        }
        return name;
    }

    // 一般GET请求都是在URL中传入参数。对于这种情况，可以直接通过注解来指定参数的校验规则
    // URL参数校验
    @RequestMapping("/test")
    public String query(@Length(min = 2, max = 10, message = "姓名长度错误，姓名长度2-10！") String name
            , @Min(value = 1, message = "年龄最小只能1") @Max(value = 99, message = "年龄最大只能99") @RequestParam(name = "age", required = true) int age) {
        System.out.println(name + "," + age);
        return name + "," + age;
    }

    @RequestMapping("/save3")
    public String save(@RequestBody @Validated({GroupA.class, Default.class}) Person person, BindingResult result){
        System.out.println(JSON.toJSONString(result.getAllErrors()));
        return "success";
    }


}
